<?php

namespace app\controller\admin\material;

use app\model\admin\material\MaterialGroup;
use app\model\admin\material\MaterialGroupGuide;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use laytp\library\Tree;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Group extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info'];
    public function initialize()
    {
        $this->model = new MaterialGroup();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with(["guide","style"])->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                $item['guide_name'] = array_column($item['guide'],"name");
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        $post = CommonFun::filterPostData($this->request->post());
        try{
            Db::startTrans();
            $data = [
                'create_time'=>   date("Y-m-d H:i:s"),
                'update_time'=>   date("Y-m-d H:i:s"),
                'material_game_id'=>   $gameId,
                'material_style_id'=>   $post['material_style_id'],
                'name'=>   $post['name'],
            ];
            $id = $this->model->insertGetId($data);
            if ($id) {
                if(isset($post['guide_ids'])){
                    $post['guide_ids'] = explode(",",$post['guide_ids']);
                    $guides = [];
                    foreach ($post['guide_ids'] as $item){
                        $guides[] = [
                          'material_game_id' =>$gameId,
                          'material_group_id' =>$id,
                          'guide_id' =>$item,
                        ];
                    }
                    if(count($guides)>0){
                        (new MaterialGroupGuide())->insertAll($guides);
                    }else{
                        Db::rollback();
                        return $this->error('请选择图鉴');
                    }
                }else{
                    Db::rollback();
                    return $this->error('请选择图鉴');
                }
                $this->clearCache();
                Db::commit();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = $this->request->post();
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $groupModel = new MaterialGroupGuide();
                $groupModel->where('material_group_id',$id)->delete();
                if(isset($post['guide_ids'])){
                    $post['guide_ids'] = explode(",",$post['guide_ids']);
                    $guides = [];
                    foreach ($post['guide_ids'] as $item){
                        $guides[] = [
                            'material_game_id' =>$info['material_game_id'],
                            'material_group_id' =>$id,
                            'guide_id' =>$item,
                        ];
                    }
                    if(count($guides)>0){
                        (new MaterialGroupGuide())->insertAll($guides);
                    }else{
                        Db::rollback();
                        return $this->error('请选择图鉴');
                    }
                }else{
                    Db::rollback();
                    return $this->error('请选择图鉴');
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if(is_object($info))$info = $info->toArray();
        $info['game'] = Db::name("material_game")->where("id", $info['material_game_id'])->find();
        $info['guide_ids'] = implode(",",(new MaterialGroupGuide())->where("material_group_id", $id)->column("guide_id"));
        return $this->success('获取成功', $info);
    }
}